package org.ceteca.explica.client.management;

/**
 * @author Juan C. Díaz (juancarlosdiaz@ceteca.net) <br>
 *         Copyright (c) 2009 Fundación Centro Tecnolóxico da Carne
 * 
 * <br>
 * <br>
 *         This program is free software: you can redistribute it and/or modify
 *         it under the terms of the GNU General Public License as published by
 *         the Free Software Foundation, either w_version 3 of the License, or (at
 *         your option) any later w_version. <br/>
 *         This program is distributed in the hope that it will be useful, but
 *         WITHOUT ANY WARRANTY 
 *         <br>without even the implied warranty of
 *         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *         General Public License for more details. <br/>
 *         You should have received a copy of the GNU General Public License
 *         along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */

import java.math.BigDecimal;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.HashMap;
import java.util.HashSet;

import org.ceteca.explica.client.ClientContext;
import org.ceteca.explica.client.gui.ExplicaDetailEntityView;
import org.ceteca.explica.client.gui.ExplicaExtensionFieldsView;
import org.ceteca.explica.client.gui.ExplicaGUIBuilder;
import org.ceteca.explica.client.gui.common.CommonClient;
import org.ceteca.explica.core.ExplicaException;
import org.ceteca.explica.core.InterfaceErrors;
import org.ceteca.explica.core.InterfaceExplica;
import org.ceteca.explica.core.common.BaseVO;
import org.ceteca.explica.core.common.MultiSelectionSubentityOT;
import org.ceteca.explica.core.common.SelectionSubentityOT;
import org.ceteca.explica.core.common.VatTypeOT;
import org.ceteca.explica.core.management.DocumentLineOT;
import org.ceteca.explica.core.management.DocumentOT;
import org.ceteca.explica.core.management.InterfaceManagement;
import org.ceteca.explica.core.management.InterfaceManagementErrors;
import org.ceteca.explica.core.management.ManagementManager;
import org.ceteca.explica.core.management.MovementOT;
import org.ceteca.explica.core.util.Converter;
import org.ceteca.explica.core.util.OperationResult;
import org.ceteca.explica.core.util.ResultMessage;
import org.ceteca.explica.core.warehouse.InterfaceWarehouse;
import org.ceteca.explica.core.warehouse.LotOT;
import org.ceteca.explica.core.warehouse.ProductOT;
import org.ceteca.explica.core.warehouse.ProductStockOT;
import org.ceteca.explica.core.warehouse.WarehouseOT;
import org.ceteca.javaglade.InterfaceGladeGtk;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;

public class DocumentLineClient extends CommonClient {

	private Text w_documentId, w_version, w_lineId, w_lineOrder,
			w_productReference, w_productDescription;
	private Text w_quantityOrder, w_quantity, w_costPrice, w_price, w_discount,
			w_vat, w_total, w_re, w_warehouse;
	private Button w_selectProduct, w_selectDocument, w_selectWarehouse, w_lot;
	private Tree w_extCatalog;

	private ExplicaDetailEntityView viewMovements;

	private LotOutSelector lotOut;

	public DocumentLineClient() {
		super(DocumentLineOT.class,
				InterfaceManagement.EXPLICA_EDIT_DOCUMENT_LINE_GLADE_PATH,
				InterfaceManagement.EXPLICA_EDIT_DOCUMENT_LINE_DIALOG_NAME);
	}

	@Override
	public void build_extension_fields_view() {
		this.extFieldsView = new ExplicaExtensionFieldsView(this.entEditView
				.getGui());
		extFieldsView.setExtCatalog(w_extCatalog);
		extFieldsView.setLogger(logger);
		extFieldsView.setEntityLauncher(this);
	}

	@Override
	public void buildSelectionSets() {
		lSelectionSubentities = new HashSet<SelectionSubentityOT>();
		lSelectionSubentities.add(new SelectionSubentityOT(
				InterfaceManagement.EXPLICA_ENTITY_DOCUMENT_ID,
				InterfaceManagement.EDIT_DOCUMENT_LINE_DOCUMENT_ID_WIDGETNAME,
				this, w_selectDocument));
		lSelectionSubentities
				.add(new SelectionSubentityOT(
						InterfaceWarehouse.EXPLICA_ENTITY_PRODUCT_ID,
						InterfaceManagement.EDIT_DOCUMENT_LINE_PRODUCT_DESCRIPTION_WIDGETNAME,
						this, w_selectProduct));
		lSelectionSubentities.add(new SelectionSubentityOT(
				InterfaceWarehouse.EXPLICA_ENTITY_WAREHOUSE_ID,
				InterfaceManagement.EDIT_DOCUMENT_LINE_WAREHOUSE_WIDGETNAME,
				this, w_selectWarehouse));
		lMultiSelectionSubentities = new HashSet<MultiSelectionSubentityOT>();

		lMultiSelectionSubentities
				.add(new MultiSelectionSubentityOT(
						InterfaceManagement.EXPLICA_ENTITY_MOVEMENT_ID,
						"treeMovements",
						this,
						this
								.getSwtWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_MOVEMENT_PANEL_WIDGETNAME),
						"movements", "documentLine"));

	}

	private void changeDocument(DocumentOT doc) {
		if (doc == null)
			return;
		int nl = doc.nextLineNumber();
		this.logger.info("Changing document: " + doc.toString());
		this.logger.info("Setting line number: " + doc.nextLineNumber());
		w_lineOrder.setText(Converter.getInstance().toString(
				doc.nextLineNumber()));
		DocumentLineOT lin = (DocumentLineOT) getEntityData();
		if (lin != null)
			changeTaxes(lin.getProduct());
	}

	private void changeProduct(ProductOT product) {
		if (product == null) {
			w_costPrice.setText("0");
			w_productDescription.setText("");
			w_productReference.setText("");
			// w_re.setText("0");
			w_vat.setText("0");
		} else {
			int resultado = ExplicaGUIBuilder
					.getInstance()
					.showConfirmationDialog(
							this.entEditView.getGui().getParentWindow()
									.getShell(),
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.MSG_MANAGEMENT_RELOAD_PRODUCT_IN_DOCUMENT),
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.MSG_MANAGEMENT_RELOAD_PRODUCT_IN_DOCUMENT_TITLE),
							SWT.ICON_QUESTION, SWT.OK + SWT.CANCEL);
			if (resultado == SWT.CANCEL)
				return;
			w_costPrice.setText(Converter.getInstance().toString(
					product.getAverageCost()));
			w_productDescription.setText(Converter.getInstance().toString(
					product.getDescription()));
			w_productReference.setText(Converter.getInstance().toString(
					product.getReference()));
			changeTaxes(product);
		}

	}

	private void changeTaxes(ProductOT product) {
		double vat = 0.0;
		double re = 0.0;
		DocumentLineOT line = (DocumentLineOT) getEntityData();

		if (product != null) {

			VatTypeOT vatType = product.getVatType();

			if (line.getDocument() != null && vatType != null) {
				int vatRegime = line.getDocument().getVatRegime();
				switch (vatRegime) {
				case 0:
					vat = vatType.getTaxPercentage().doubleValue();
					re = 0.0;
					break;
				case 1:
					break;
				case 2:
					vat = 0.0;
					re = 0.0;
					break;
				case 3:
					vat = vatType.getTaxPercentage().doubleValue();
					re = vatType.getRecEquiPercentage().doubleValue();
					break;

				}
			}

		}
		w_re.setText(Converter.getInstance().toString(re));
		w_vat.setText(Converter.getInstance().toString(vat));
		recalculate();
	}

	@Override
	public void clearEntityData() {

		DocumentLineOT c = new DocumentLineOT();
		if (isDetail())
			if (this.entityDetailView.getSubentityData().getParentEntity()
					.getEntity().getKey().equals(
							InterfaceManagement.EXPLICA_ENTITY_DOCUMENT_ID)) {
				DocumentOT parent = (DocumentOT) entityDetailView
						.getSubentityData().getParentEntity().getEntityData();
				if (parent != null) {
					c.setDocument(parent);
					changeDocument(parent);
					c.setOrder(parent.nextLineNumber());
				}

			}

		setWidgetsValues(c);

	}

	@Override
	public BaseVO getEntityData() {
		DocumentLineOT ent = new DocumentLineOT();
		if (this.entEditView != null) {
			ent.setCostPrice(Converter.getInstance().parseBigDecimal(
					w_costPrice.getText()));
			ent.setDescription(Converter.getInstance().toString(
					w_productDescription.getText()));
			ent.setDiscount(Converter.getInstance().parseBigDecimal(
					w_discount.getText()));
			ent.setOrder(Converter.getInstance().parseInteger(
					w_lineOrder.getText()));
			ent.setOrderQuantity(Converter.getInstance().parseBigDecimal(
					w_quantityOrder.getText()));
			ent.setPrice(Converter.getInstance().parseBigDecimal(
					w_price.getText()));
			ent.setProductReference(Converter.getInstance().toString(
					w_productReference.getText()));
			ent.setQuantity(Converter.getInstance().parseBigDecimal(
					w_quantity.getText()));
			ent.setRe(Converter.getInstance().parseBigDecimal(w_re.getText()));
			ent
					.setVat(Converter.getInstance().parseBigDecimal(
							w_vat.getText()));

			ent.setDescription(Converter.getInstance().toString(
					w_productDescription.getText()));

			ent.setDocument((DocumentOT) w_documentId.getData());
			ent.setProduct((ProductOT) w_productDescription.getData());

			ent.setWarehouse(((WarehouseOT) w_warehouse.getData()));

			if (ent.getMovements() == null)
				ent.setMovements(new HashSet<MovementOT>());

			ent.getMovements().clear();
			if (viewMovements != null)
				ent.getMovements().addAll(viewMovements.getRegistries());

			if (selectedEntity != null) {
				ent.setVersion(((DocumentLineOT) selectedEntity).getVersion());
				ent.setIdDocumentLine(((DocumentLineOT) selectedEntity)
						.getIdDocumentLine());
			}

		}
		return ent;
	}

	@Override
	public void getWidgets() {

		int codError = 0;
		w_documentId = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_DOCUMENT_ID_WIDGETNAME);
		w_lineId = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_CODE_WIDGETNAME);
		w_productDescription = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_PRODUCT_DESCRIPTION_WIDGETNAME);
		w_lineOrder = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_ORDER_WIDGETNAME);
		w_productReference = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_PRODUCT_REFERENCE_WIDGETNAME);
		w_quantityOrder = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_QUANTITY_ORDER_WIDGETNAME);
		w_quantity = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_QUANTITY_WIDGETNAME);
		w_costPrice = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_COST_PRICE_WIDGETNAME);
		w_price = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_PRICE_WIDGETNAME);
		w_discount = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_DISCOUNT_WIDGETNAME);
		w_re = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_RE_WIDGETNAME);
		w_vat = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_VAT_WIDGETNAME);
		w_total = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_TOTAL_WIDGETNAME);
		w_warehouse = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_WAREHOUSE_WIDGETNAME);
		w_version = (Text) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_VERSION_WIDGETNAME);
		w_selectProduct = (Button) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_SELECT_PRODCUT_BUTTON_NAME);
		w_selectWarehouse = (Button) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_SELECT_WAREHOUSE_BUTTON_NAME);
		w_selectDocument = (Button) this
				.getWidget(InterfaceManagement.EDIT_DOCUMENT_LINE_SELECT_DOCUMENT_BUTTON_NAME);

		if (this.entEditView != null)
			viewMovements = this.entEditView
					.getMultiSelectEntityView(InterfaceManagement.EXPLICA_ENTITY_MOVEMENT_ID);

		if (w_costPrice == null)
			codError = 1;
		if (w_discount == null)
			codError = 2;
		if (w_documentId == null)
			codError = 3;
		if (w_lineId == null)
			codError = 4;
		if (w_lineOrder == null)
			codError = 5;
		if (w_price == null)
			codError = 6;
		if (w_productDescription == null)
			codError = 7;
		if (w_productReference == null)
			codError = 9;
		if (w_quantity == null)
			codError = 10;
		if (w_quantityOrder == null)
			codError = 11;
		// if (w_re == null)
		// codError = 12;
		if (w_selectDocument == null)
			codError = 13;
		if (w_selectProduct == null)
			codError = 14;
		if (w_total == null)
			codError = 15;
		if (w_vat == null)
			codError = 16;
		if (w_version == null)
			codError = 17;
		if (w_lineId == null)
			codError = 18;
		if (w_warehouse == null)
			codError = 20;
		if (w_selectWarehouse == null)
			codError = 21;
		w_extCatalog = (Tree) getWidget(InterfaceManagement.EXPLICA_DOCUMENT_LINE_ENTITY_EXTENSION_CATALOG_NAME);

		if (w_extCatalog == null)
			codError = 19;

		w_lot = (Button) getWidget(InterfaceManagement.EXPLICA_DOCUMENT_LINE_BUTTON_LOTS_WIDGETNAME);
		if (w_lot == null)
			codError = 22;

		if (codError != 0)
			fireExceptionAndExit("Error obteniendo widgets " + codError);

	}

	@Override
	public void init_specific_components() {

		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, w_discount,
				"on_data_changed", this);
		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, w_price,
				"on_data_changed", this);
		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, w_quantity,
				"on_data_changed", this);
		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CLICKED, w_lot,
				"on_lot_clicked", this);

		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, w_vat,
				"on_data_changed", this);

		lotOut = new LotOutSelector(this);
		lotOut.build();

	}

	public void on_data_changed(Event e) {

		recalculate();
	}

	private void recalculate() {
		DocumentLineOT doc = (DocumentLineOT) getEntityData();
		setTotalsWidgetsValues(doc);
	}

	@Override
	public void selectSubentity(String parentFieldId, BaseVO subentityOT) {

		if (subentityOT.getEntityId().equals(
				InterfaceWarehouse.EXPLICA_ENTITY_PRODUCT_ID)) {
			ProductOT product = (ProductOT) subentityOT;
			changeProduct(product);
		}
		if (subentityOT.getEntityId().equals(
				InterfaceManagement.EXPLICA_ENTITY_DOCUMENT_ID)) {
			DocumentOT doc = (DocumentOT) subentityOT;
			changeDocument(doc);
		}
		super.selectSubentity(parentFieldId, subentityOT);

	}

	@Override
	public void setEditionMode(boolean enabled) {
		w_version.setEnabled(false);
		w_total.setEnabled(false);
		w_lineId.setEnabled(false);
		w_costPrice.setEnabled(false);

		if ((w_lineId.getText().equals("0") || w_lineId.getText().isEmpty())
				&& !isDetail()) {
			w_documentId.setEnabled(enabled);
			w_selectDocument.setEnabled(enabled);
		} else {
			w_documentId.setEnabled(false);
			w_selectDocument.setEnabled(false);
		}
		w_discount.setEnabled(enabled);
		w_lineOrder.setEnabled(enabled);
		w_price.setEnabled(enabled);
		w_productDescription.setEnabled(enabled);
		w_productReference.setEnabled(enabled);
		w_quantity.setEnabled(enabled);
		w_quantityOrder.setEnabled(enabled);
		w_re.setEnabled(enabled);
		w_selectProduct.setEnabled(enabled);
		w_total.setEnabled(false);
		w_vat.setEnabled(enabled);
		w_extCatalog.setEnabled(enabled);
		w_warehouse.setEnabled(enabled);
		w_selectWarehouse.setEnabled(enabled);

	}

	private void setTotalsWidgetsValues(DocumentLineOT doc) {
		w_total.setText(Converter.getInstance().toString(doc.getGrossAmount()));
	}

	@Override
	public void setWidgetsValues(BaseVO entity) {
		DocumentLineOT ent = (DocumentLineOT) entity;

		w_lineId.setText(Converter.getInstance().toString(
				ent.getIdDocumentLine()));
		w_version.setText(Converter.getInstance().toString(ent.getVersion()));
		w_costPrice.setText(Converter.getInstance()
				.toString(ent.getCostPrice()));
		w_discount.setText(Converter.getInstance().toString(ent.getDiscount()));
		w_lineOrder.setText(Converter.getInstance().toString(ent.getOrder()));
		w_price.setText(Converter.getInstance().toString(ent.getPrice()));
		w_productDescription.setText(Converter.getInstance().toString(
				ent.getDescription()));
		w_productReference.setText(Converter.getInstance().toString(
				ent.getProductReference()));
		w_quantity.setText(Converter.getInstance().toString(ent.getQuantity()));
		w_quantityOrder.setText(Converter.getInstance()
				.toString(ent.getOrder()));
		w_re.setText(Converter.getInstance().toString(ent.getRe()));
		w_vat.setText(Converter.getInstance().toString(ent.getVat()));
		w_productDescription.setText(Converter.getInstance().toString(
				ent.getDescription()));
		setTotalsWidgetsValues(ent);

		if (ent.getDocument() != null) {
			w_documentId.setText(Converter.getInstance().toString(
					ent.getDocument().getIdDocument()));

		} else {
			w_documentId.setText("");
		}
		w_documentId.setData(ent.getDocument());

		if (ent.getWarehouse() != null) {
			w_warehouse.setText(ent.getWarehouse().getDescription());
		} else {
			w_warehouse.setText("");
		}
		w_warehouse.setData(ent.getWarehouse());

		if (ent.getProduct() != null) {
			w_productDescription.setData(ent.getProduct());
		}

		if (viewMovements != null)
			viewMovements.setRegistries(ent.getMovements());

		if (extFieldsView != null)
			extFieldsView.clear();

		if (ent.getDocument() != null)
			if (ent.getDocument().getDocumentType() != null)
				if (ent.getDocument().getDocumentType().getExtTableLines() != null) {
					extFieldsView.setExtTable(ent.getDocument()
							.getDocumentType().getExtTableLines());
					fillEntityExtensionTable(ent.getIdDocumentLine());

				}

	}

	public OperationResult generateMovements(
			HashMap<ProductStockOT, BigDecimal> asigments) {

		OperationResult result = new OperationResult();

		try {
			ManagementManager manager = getRemoteManagement();
			//manager.deleteMovements((DocumentLineOT) this.getEntityData());

			System.out.println("Generando movimientos");
			HashSet<MovementOT> movements = new HashSet<MovementOT>();
			DocumentLineOT line = (DocumentLineOT) getEntityData();
			for (ProductStockOT s : asigments.keySet()) {
				System.out.println("Generando movimiento lote: "
						+ s.getLot().getNumber() + " cantidad: "
						+ asigments.get(s));
				MovementOT m = generateMovement(line, asigments.get(s), s
						.getLot());
				if (m != null)
					movements.add(m);
			}
			System.out
					.println("Mostrando " + movements.size() + " movimientos");
			if (viewMovements != null)
				viewMovements.setRegistries(movements);

		/*} catch (RemoteException e) {
			result.addResultMessage(OperationResult.RESULT_ERROR,
					new ResultMessage(OperationResult.RESULT_ERROR, e
							.getCause()));
			e.printStackTrace();
			*/
		} catch (ExplicaException e) {
			result.addResultMessage(OperationResult.RESULT_ERROR,
					new ResultMessage(OperationResult.RESULT_ERROR, e
							.getCause()));
			e.printStackTrace();
		}
		return result;

	}

	@Override
	public OperationResult validateEntity() {
		
		
		/*
		OperationResult result = new OperationResult();
		
		if (lotOut.isLots_selected())
			result.add(lotOut.validate());
		else

			result
					.addResultMessage(
							OperationResult.RESULT_ERROR,
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.newResultMessage(
											InterfaceManagementErrors.MSG_LOT_STOCK_VALIDATE_ERROR));
		return result;
		*/
		return null;
		
	}

	@Override
	public void fillEntityData() {
		if (this.selectedEntity != null && this.entEditView != null) {
			getWidgets();
			setWidgetsValues((DocumentLineOT) selectedEntity);
		}
	}

	public MovementOT generateMovement(DocumentLineOT line,
			BigDecimal quantity, LotOT lot) {
		if (line == null) {
			System.out
					.println("No se genera el movimiento porque la linea es nula");
			return null;
		}
		if (line.getDocument() == null) {
			System.out
					.println("No se genera el movimiento porque el documento es nulo");
			return null;
		}
		if (line.getDocument().getDocumentType() == null) {
			System.out
					.println("No se genera el movimeinto porque el tipo de documento es nulo");
			return null;
		}
		if (!line.getDocument().getDocumentType().getModifyStock()) {
			System.out
					.println("No se genera el movimiento porque el tipo de documento no mofifica stock ");
			return null;
		}
		MovementOT movement = new MovementOT();
		movement.setDocumentLine(line);
		movement.setCostPrice(line.getCostPrice());
		movement.setDate(line.getDocument().getDateDocument());
		movement.setIncrementStock(line.getDocument().getDocumentType()
				.getIncrementStock());
		/*
		 * if (lot.getAvailable().compareTo(quantity)>=0 ){
		 * movement.setLot(lot); movement.setQuantity(quantity); }
		 */
		movement.setLot(lot);
		movement.setPartner(line.getDocument().getPartner());
		movement.setProduct(line.getProduct());
		movement.setSalesPrice(line.getPrice());
		movement.setWarehouse(line.getDocument().getWarehouse());
		movement.setQuantity(line.getQuantity());

		return movement;
	}

	public void on_lot_clicked(Event e) {
		this.logger.info("Showing lot selection dialog");
		DocumentLineOT entity = (DocumentLineOT) getEntityData();
		lotOut.setProduct(entity.getProduct());
		lotOut.setWarehouse(entity.getWarehouse());
		lotOut.setQuantity(entity.getQuantity());

		lotOut.show();
	}

	/**
	 * 
	 * Get access to the server via rmi
	 * 
	 * @return ManagementManager. An instance of ManagementManager used to
	 *         invoke operations on the server
	 * @throws ExplicaException
	 */
	protected ManagementManager getRemoteManagement() throws ExplicaException {

		try {

			Registry registry = LocateRegistry
					.getRegistry(InterfaceExplica.RMI_REGISTRY_PORT);

			ManagementManager manager = (ManagementManager) registry
					.lookup(InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME);

			return manager;
		} catch (AccessException aEx) {
			aEx.printStackTrace();
			throw new ExplicaException(
					ClientContext
							.getInstance()
							.getMsgCatalog()
							.newResultMessage(
									InterfaceErrors.ERR_RMI_NO_ACCESS,
									aEx,
									(Object) InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME,
									(Object) null));
		} catch (NotBoundException nEx) {
			nEx.printStackTrace();
			throw new ExplicaException(
					ClientContext
							.getInstance()
							.getMsgCatalog()
							.newResultMessage(
									InterfaceErrors.ERR_RMI_NOT_BOUND,
									nEx,
									(Object) InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME,
									(Object) null));
		} catch (RemoteException rEx) {
			rEx.printStackTrace();
			throw new ExplicaException(
					ClientContext
							.getInstance()
							.getMsgCatalog()
							.newResultMessage(
									InterfaceErrors.ERR_RMI_METHOD_NOT_FOUND,
									rEx,
									(Object) InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME,
									(Object) null));
		}
	}

}
